import { login as loginApi } from '@/api/login'
import router from '@/router'
import { setTokenTime } from '@/utils/auth'
import { ElNotification } from 'element-plus'
export default {
  namespaced: true,
  state: () => ({
    token: localStorage.getItem('token') || '',
    dialogVisible: false,
    logStatus: true
  }),
  mutations: {
    setToken(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    setDialogVisible(state) {
      state.dialogVisible = !state.dialogVisible
    },
    setLogStatus(state, status) {
      state.logStatus = status
    }
  },
  actions: {
    login({ commit }, userInfo) {
      const houer = new Date().getHours()
      let str = ''
      if (houer >= 20 || houer < 6) {
        str = '晚上好'
      } else if (houer >= 6 && houer < 12) {
        str = '上午好'
      } else if (houer >= 12 && houer < 20) {
        str = '下午好'
      }
      return new Promise((resolve, reject) => {
        loginApi(userInfo)
          .then((res) => {
            ElNotification({
              title: '登录成功',
              message: `${str}${userInfo.name} , 欢迎回来🌈🎉🎉🎉`,
              type: 'success',
              duration: 2000
            })
            const { data } = res.data
            commit('user/setProfile', data, { root: true })
            commit('setToken', data.token)
            commit('setLogStatus', false)
            commit('setDialogVisible')
            setTokenTime()
            const currentRoute = router.currentRoute.value.path
            if (currentRoute) {
              router.replace(currentRoute)
            } else {
              router.replace('/')
            }
            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    // 退出
    logout({ commit }) {
      commit('setToken', '')
      localStorage.clear()

      commit('setLogStatus', true)
      router.replace('/')
    }
  }
}
